package com.it.data_queue.blocking_queue;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 单锁实现
 *
 * @author: Coke
 * @DateTime: 2023/06/18/13:04
 **/
public class BlockingQueue1<E> implements BlockingQueue<E> {
    
    private final E[] array;
    private int head;
    private int tail;
    private AtomicInteger size = new AtomicInteger();
    private ReentrantLock lock = new ReentrantLock();
    private Condition headWaits = lock.newCondition();
    private Condition tailWaits = lock.newCondition();
    
    public BlockingQueue1 (int capacity) {
        array = (E[]) new Object[capacity];
    }
    
    @Override
    public void offer (E e) throws InterruptedException {
        lock.lockInterruptibly();
        try {
            while (isPull()) {
                tailWaits.await();
            }
            array[tail] = e;
            if (++ tail == array.length) {
                tail = 0;
            }
            size.getAndIncrement();
            headWaits.signal();
        } finally {
            lock.unlock();
        }
    }
    
    @Override
    public boolean offer (E e, long timeout) throws InterruptedException {
        lock.lockInterruptibly();
        try {
            long l = TimeUnit.MILLISECONDS.toNanos(timeout);
            while (isPull()) {
                if (l <= 0) {
                    return false;
                }
                l = tailWaits.awaitNanos(l);
            }
            array[tail] = e;
            if (++ tail == array.length) {
                tail = 0;
            }
            size.getAndIncrement();
            headWaits.signal();
            return true;
        } finally {
            lock.unlock();
        }
    }
    
    @Override
    public E pool () throws InterruptedException {
        lock.lockInterruptibly();
        try {
            while (isEmpty()) {
                headWaits.await();
            }
            E e = array[head];
            array[head] = null;
            if (++ head == array.length) {
                head = 0;
            }
            size.getAndDecrement();
            tailWaits.signal();
            return e;
        } finally {
            lock.unlock();
        }
    }
    
    private boolean isEmpty () {
        return size.get() == 0;
    }
    
    private boolean isPull () {
        return size.get() == array.length;
    }
}
